package com.code.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;

public class FileUtil {
	public static void writeStringToFile(File file, String data, String encoding)
			throws IOException {
		OutputStream out = new FileOutputStream(file);
		try {
			out.write(StrUtil.isEmpty(data) ? data.getBytes() : data
					.getBytes(encoding));
		} finally {
			out.close();
		}
	}

	public static String readFileToString(File file, String encoding)
			throws IOException {
		Reader rd = null;
		try {
			rd = StrUtil.isEmpty(encoding) ? new InputStreamReader(
					new FileInputStream(file)) : new InputStreamReader(
					new FileInputStream(file), encoding);
			StringWriter sw = new StringWriter();
			char[] buffer = new char[1024];
			int len = 0;
			while (-1 != (len = rd.read(buffer))) {
				sw.write(buffer, 0, len);
			}
			return sw.toString();
		} finally {
			if (rd != null)
				rd.close();
		}
	}
}
